package cn.tedu.lbs.stock.web.service;

import cn.tedu.lbs.stock.web.repository.StockRepository;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.pojo.stock.param.CouponStockParam;
import com.tarena.lbs.pojo.stock.po.CouponStockPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StockService {
    @Autowired
    private StockRepository stockRepository;
    public boolean initStock(CouponStockParam param) {
        //做一件事 初始化po 写入数据库
        CouponStockPO poParam=new CouponStockPO();
        poParam.setCouponId(param.getCouponId());
        poParam.setBusinessId(param.getBusinessId());
        poParam.setNum(param.getNum());
        //创建和修改时间
        poParam.setCreateAt(new java.util.Date());
        poParam.setUpdateAt(new java.util.Date());
        return stockRepository.save(poParam);
    }

    public Integer getStock(Integer couponId) throws BusinessException {
        //select num from coupon_stock where coupon_id=?
        QueryWrapper<CouponStockPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("coupon_id",couponId);
        CouponStockPO stockPO = stockRepository.getOne(queryWrapper);
        Asserts.isTrue(stockPO==null,new BusinessException("-2","优惠券库存不存在"));
        return stockPO.getNum();
    }

    public boolean reduceStock(Integer couponId, Integer num) {
        //初步设计 update coupon_stock set num=num-? where coupon_id=?
        return stockRepository.reduceStock(couponId,num);
    }
}
